package data;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ValidateImport {
    public static final String URL_LEGAL_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";

    public static void main(String[] args) throws IOException, InvalidImport {
        validate("data/import/extramobi/");
    }

    public static void validate(String path) throws IOException, InvalidImport {
        File importFolder = new File(path);

        for (File file : importFolder.listFiles()) {
            if (file.getName().contains(".svn")) {
                continue;
            }
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            int lineCount = 1;
            while ((line = reader.readLine()) != null) {
                if (line.contains("null") ||
                        line.contains("${") ||
                        line.contains("#{") ||
                        line.contains("\\")) {
                    throw new InvalidImport("Wrong line: " + file + ": " + lineCount);
                }
                lineCount++;
            }
            reader.close();
        }
    }

    public static void validateImages() {

    }

    public static void validate(Map<String, List<ItemData>> data) throws InvalidImport {
        List<String> uniqueArticles = new ArrayList<String>();
        for (String file : data.keySet()) {
            List<ItemData> dataByFile = data.get(file);
            for (ItemData item : dataByFile) {
                if (!item.category) {
                    validateArticle(item);
                    if (uniqueArticles.contains(item.article) && item.article.length() > 1) {
                        System.err.println("Article not unique " + item);
                    } else {
                        uniqueArticles.add(item.article);
                    }
                }
                validateUrl(item);
                if (item.modelsData != null) {
                    for (ItemData itemModel : item.modelsData) {
                        validateUrl(itemModel);
                    }
                }
            }
        }
    }

    private static void validateUrl(ItemData item) throws InvalidImport {
        for (char c : item.url.toCharArray()) {
            if (!URL_LEGAL_CHARS.contains(c + "")) {
                throw new InvalidImport("Illegal character in item url: " + c + " " + item);
            }
        }
    }

    private static void validateArticle(ItemData item) throws InvalidImport {
        if (!item.category && item.article.length() != 7 && !item.engname.contains("Remont")) {
            throw new InvalidImport("Out of article length: " + item);
        }
    }
}

class InvalidImport extends Exception {

    public InvalidImport(String message) {
        super(message);
    }
}